<template>
  <tab-head></tab-head>
  <el-table :data="state.tableData" style="width: 100%">
    <el-table-column fixed prop="id" label="编号" width="120"/>
    <el-table-column prop="title" label="标题" width="240"/>
    <el-table-column prop="createby" label="创建人" width="120"/>
    <el-table-column prop="category" label="类别" width="120"/>
    <el-table-column prop="description" label="摘要" />
    <el-table-column fixed="right" label="操作" width="300">
      <template #default="scope">
        <el-button type="primary" size="small" @click="toMarkDown(scope.row.id)">
          <el-icon>
            <EditPen/>
          </el-icon>
          编辑内容
        </el-button>
        <el-button type="warning" size="small" @click="openEdit(scope.row)">
          <el-icon>
            <Edit/>
          </el-icon>
          修改信息
        </el-button>
        <el-button type="danger" size="small" @click="openDele(scope.row.id)">
          <el-icon>
            <Close/>
          </el-icon>
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-button @click="dialogFormVisible = true">
    <el-icon>
      <Plus/>
    </el-icon>
    添加
  </el-button>
  <!--添加和修改的表格-->
  <el-dialog v-model="dialogFormVisible" title="博客信息" width="40%">
    <el-form :model="state.form" :rules="state.rules" ref="ruleFormRef" label-width="120px" style="width: 85%">
      <el-form-item label="id" prop="编号">
        <el-input v-model="state.form.id" autocomplete="off" placeholder="请输入编号"/>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="state.form.title" autocomplete="off" placeholder="请输入标题"/>
      </el-form-item>
      <el-form-item label="创建人" prop="user_id">
        <el-input v-model="state.form.createby" autocomplete="off" placeholder="请输入创建人"/>
      </el-form-item>
      <el-form-item label="类别" prop="category">
        <el-select v-model="state.form.category" placeholder="请选择文章类别">
          <el-option label="Java" value="Java" />
          <el-option label="后端" value="后端" />
          <el-option label="前端" value="前端" />
          <el-option label="数据库" value="数据库" />
          <el-option label="web基础" value="web基础" />
          <el-option label="工具使用" value="工具使用" />
        </el-select>
      </el-form-item>
      <el-form-item label="摘要" prop="description">
        <el-input v-model="state.form.description" autocomplete="off" placeholder="请输入摘要"/>
      </el-form-item>
    </el-form>
    <template #footer="scope">
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save()"
        >提交</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import TabHead from "../components/TabHead.vue";
import {getCurrentInstance, reactive, ref} from "vue";
import request from "../request";
import {ElMessage, ElMessageBox} from 'element-plus'
import { useRouter ,useRoute} from "vue-router";

const {proxy} = getCurrentInstance()

//统一管理变量
const state = reactive({
  tableData: [],
  form: {
    //edit用于判断请求是修改还是添加（两者共用一个表单）
    edit: false,
    user_id:localStorage.getItem("user_id")
  },
  rules: {
    //表单校验
  }
})

//加载页面信息
const load = () => {
  request.get("/article/findAll").then(res => {
    state.tableData = res
  })
}
load()

//保存模块（用于添加和修改）
const dialogFormVisible = ref(false)
const save = () => {
  //edit===true表明这是修改请求
  if (state.form.edit === true) {
    proxy.$refs.ruleFormRef.validate((valid) => {
      if (valid) {
        dialogFormVisible.value = false
        //获取未修改前的id
        let temp = state.form.id
        for (const table of state.tableData) {
          if (table.edit === true) {
            table.edit = false
            state.form.id = table.id
          }
        }
        //先用原来的id修改其它新信息
        request.put("/article/updateById", state.form).then((res) => {
          if (res === true) {
            state.form.id = temp
            //再用新title修改id
            request.put("/article/updateByTitle", state.form).then((res) => {
              if (res === true) {
                ElMessage.success('修改成功')

              } else {
                ElMessage.error('学号修改失败')
              }
              load()
            })
          } else {
            ElMessage.error('修改失败')
          }
          //初始化form对象
          state.form = {
            edit: false,
            user_id:localStorage.getItem("user_id")
          }
        })
      }
    })
  }
  //edit===false表明这是添加请求
  else {
    proxy.$refs.ruleFormRef.validate((valid) => {
      if (valid) {
        request.post("/article/add", state.form).then(res => {
          if (res === true) {
            dialogFormVisible.value = false
            ElMessage.success('添加成功')
            state.form = {
              edit: false,
              user_id:localStorage.getItem("user_id")
            }
            load()
          } else {
            ElMessage.error('添加失败')
          }
        })
      }
    })
  }
}

//修改模块
const openEdit = (row) => {
  //JSON.stringify() 方法将一个JavaScript 对象或值转换为JSON 字符串
  //JSON.parse() 方法用来解析JSON 字符串，构造由字符串描述的JavaScript 值或对象
  /*
  state.form = JSON.parse(JSON.stringify(student)) 相当于吧student（scope.row）的信息拿出来再给form，
  而不直接用student（scope.row）对象去操作数据，解决用户不点击提交，只是修改内容，前端显示的数据就会被改变
  */
  row.edit = true
  state.form = JSON.parse(JSON.stringify(row))
  dialogFormVisible.value = true
}

//确认删除弹窗+删除模块
const openDele = (id) => {
  ElMessageBox.confirm(
      '确定要删除此用户？',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        request.delete("/article/dele/" + id).then(res => {
          if (res === true) {
            ElMessage.success('删除成功')
            load()
          } else {
            ElMessage.error('删除失败')
          }
        })
      })
      .catch(() => {
        ElMessage.info('删除取消')
      })
}

//取消模块
const cancel = () => {
  dialogFormVisible.value = false
  state.form = {
    edit: false
  }
}

//转跳到编辑页
const router = useRouter();
const toMarkDown = (id) => {
  router.push({
    name: "MarkDown",
    params: {
      id
    }
  })
}
</script>